<template>
    <div class="mainContent">
        <div class="boxWrapper searchForm">
            <el-form :inline="true" size="small">
                <el-form-item label="缺陷类型">
                    <el-select v-model="CATEGROY" placeholder="请选择" @change="handleChangeCategroy" style="width:160px">
                        <el-option label="全部台账" :value="0"></el-option>
                        <el-option label="监测设施" :value="1"></el-option>
                        <el-option label="在线安全" :value="2"></el-option>
                        <el-option label="巡视安全" :value="3"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="时间范围">
                <el-date-picker
                    v-model="startTime"
                    format="yyyy年MM月dd日"
                    value-format="yyyy/MM/dd"
                    type="date"
                    placeholder="选择日期">
                </el-date-picker>
                至
                <el-date-picker
                    v-model="endTime"
                    format="yyyy年MM月dd日"
                    value-format="yyyy/MM/dd"
                    type="date"
                    placeholder="选择日期">
                </el-date-picker>
                <el-button type="primary" size="small" @click="handleChangeCategroy(CATEGROY)" style="margin-left:8px" icon="el-icon-search">查询</el-button>
                <el-tooltip class="item" effect="dark" content="无新增权限" placement="top-start" :disabled="permissions.showRoleAdd == 1">
                    <el-button type="primary" size="small" @click="handleAddLedger(false)" style="height:32px;margin-top:0px;" icon="el-icon-plus" :disabled="permissions.showRoleAdd == 0">新建台帐</el-button>
                </el-tooltip>
                </el-form-item>
            </el-form>
        </div>
        <div class="tableContent boxWrapper">
            <div class="stats-info" v-if="tableData.length > 0">
                <span class="stat-item">
                    <i class="el-icon-document"></i>
                    共 {{ stats.total }} 条记录
                </span>
                <span class="stat-item">
                    <i class="el-icon-success greenText"></i>
                    已处理: {{ stats.completed }}条
                </span>
                <span class="stat-item">
                    <i class="el-icon-warning blueText"></i>
                    待处理: {{ stats.pending }}条
                </span>
                <span class="stat-item">
                    <i class="el-icon-warning orangeText"></i>
                    重复缺陷: {{ stats.repeated }}条
                </span>
            </div>
            <el-table id="oIncomTable" :data="tableData" border stripe  height="calc(100vh - 260px)" width="100%">
                <el-table-column
                    type="index"
                    label="序号"
                    width="60" align="center"></el-table-column>
                <el-table-column align="center"  prop="code" label="缺陷单号" width="170"></el-table-column>
                    <el-table-column  align="center" prop="cont" label="消缺内容"  width="220" show-overflow-tooltip></el-table-column>
                    <el-table-column align="center" prop="foundTime" label="发现时间"  width="170"></el-table-column>
                    <el-table-column align="center" prop="recorderName" label="填报人"  width="120">
                      <template slot-scope="scope">
                          <i class="el-icon-user-solid blueText"></i>
                          <span>{{ scope.row.recorderName }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column align="center"  prop="CATEGROY" label="缺陷类型"  width="120">
                        <template slot-scope="scope">
                        <el-tag type="warning" v-if="scope.row.CATEGROY == 1" size="small">监测设施</el-tag>
                        <el-tag type="success" v-if="scope.row.CATEGROY == 2" size="small">在线安全</el-tag>
                        <el-tag v-if="scope.row.CATEGROY == 3" size="small">巡视安全</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column align="center" prop="equipment" label="对应设备"  width="120"></el-table-column>
                    <el-table-column align="center" prop="tp" label="缺陷类别"  width="160"></el-table-column>
                    <el-table-column  align="center" prop="describe" label="缺陷描述"  width="120" show-overflow-tooltip></el-table-column>
                    <el-table-column align="center" prop="provTime" label="规定消缺时间" width="170"></el-table-column>
                    <el-table-column align="center" prop="finishTime" label="实际消缺时间" width="170"></el-table-column>
                    <el-table-column align="center" prop="result" label="消缺情况" show-overflow-tooltip  width="120"></el-table-column>
                    <el-table-column align="center" prop="repeat" label="重复缺陷"  width="120">
                        <template slot-scope="scope">
                        <p v-if="scope.row.repeat == 1" class="redText">是</p>
                        <p v-if="scope.row.repeat == 0" class="greenText">否</p>
                        </template>
                    </el-table-column>
                    <el-table-column align="center" prop="status" label="消缺状态"  width="120">
                        <template slot-scope="scope">
                        <el-tag type="success" v-if="scope.row.status == 1" size="small">已消缺</el-tag>
                        <el-tag type="danger" v-if="scope.row.status == 0" size="small">未消缺</el-tag>
                        </template>
                    </el-table-column> 
                    <el-table-column align="center" prop="recordTime" label="记录时间"  width="170"></el-table-column>
                    <el-table-column align="center" prop="prosessName" label="指派人" width="170">
                        <template slot-scope="scope">
                        <el-select placeholder="请选择指派人" :value="scope.row.prosessName" v-if="(scope.row.prosessName == '' || scope.row.prosessName == null) && scope.row.status == 0" size="small" @change="handleChangeLedgerSet(scope.row,$event)" :disabled="!permissions.showRoleEdit">
                            <el-option
                            v-for="item in userList"
                            :key="item.id"
                            :label="item.userTrueName"
                            :value="item.id">
                            </el-option>
                        </el-select>
                        <span v-else>
                          {{scope.row.prosessName}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column align="center" prop="date" label="当前进程" width="120">
                        <template slot-scope="scope">
                        <el-button  type="text"  @click="handleGetLedgerInfo(scope.row)" icon="el-icon-document">详情</el-button>
                        </template>
                    </el-table-column>
                    <el-table-column align="center" prop="date" label="操作" width="200" fixed="right">
                        <template slot-scope="scope">
                            <el-link  type="success" @click="handleSetStatus(scope.row)" :underline="false" v-if="scope.row.status == 0 && permissions.showRoleEdit" icon="el-icon-coordinate">消缺</el-link>

                            <el-tooltip class="item" effect="dark" content="无编辑权限" placement="top-start" :disabled="permissions.showRoleEdit == 1">
                                <el-link @click="handleAddLedger(true,scope.row)" icon="el-icon-edit" :underline="false" type="primary" style="margin-left:10px" :disabled="permissions.showRoleEdit == 0">编辑</el-link>
                            </el-tooltip>

                            <el-tooltip class="item" effect="dark" content="无删除权限" placement="top-start" :disabled="permissions.showRoleDel == 1">
                                <el-link  type="danger"  @click="handleDelLedger(scope.row)" :underline="false" icon="el-icon-delete" style="margin-left:10px" :disabled="permissions.showRoleDel == 0">删除</el-link>
                            </el-tooltip>
                        </template>
                    </el-table-column>
            </el-table>


        <el-dialog
            title="台账详情"
            :visible.sync="infoDialog"
            width="600px"
            class="info-dialog"
            >
            <div class="info-content">
                <el-descriptions :column="1" border>
                <el-descriptions-item label="发起人">
                    <el-tag size="small">{{ infoData.AssignerName || '暂无' }}</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="发起时间">
                    {{ infoData.assignTime || '暂无' }}
                </el-descriptions-item>
                <el-descriptions-item label="处理人">
                    <el-tag size="small">{{ infoData.ProcessorName || '暂无' }}</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="处理时间">
                    {{ infoData.ProcessTime || '暂无' }}
                </el-descriptions-item>
                </el-descriptions>
            </div>
        </el-dialog>


        <el-dialog
            title="消缺设置"
            :visible.sync="dialogStatusVisible"
            width="600px"
            class="status-dialog"
            >
            <div class="status-form">
                <el-form 
                :model="changeStatusForm" 
                label-width="100px" 
                :rules="rulestatus" 
                ref="changeStatusForm"
                >
                <el-form-item label="消缺状态" prop="status">
                    <el-select v-model="changeStatusForm.status" placeholder="请选择">
                    <el-option label="未处理" :value="0"></el-option>
                    <el-option label="已处理" :value="1"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="消缺结果" prop="result" >
                    <el-input 
                    type="textarea" 
                    :rows="6" 
                    v-model="changeStatusForm.result" 
                    placeholder="请输入消缺结果"
                    maxlength="500"
                    show-word-limit
                    ></el-input>
                </el-form-item>
                </el-form>
            </div>
            <div class="dialog-footer">
                <el-button @click="dialogStatusVisible = false" size="small" icon="el-icon-circle-close" class="cancel-btn">取消</el-button>
                <el-button type="primary" @click="handleSaveStatus" size="small" icon="el-icon-circle-check" class="confirm-btn">保存设置</el-button>
            </div>
        </el-dialog>

        <accountSetting :visible.sync="dialogVisible" :formLedger="formLedger" @handleCloseLedger="handleClose"  @handleSaveLedger="handleSaveForm" isLeaderPage @changeCategroy="changeCategroy"/>
        </div>
    </div>
</template>

<script>
import {sysLeaderGetList,getLedgerByTp,GetORGUser,ledgerProssAdd,getLedgerProcess,sysLeaderSetStatus,sysLeaderAdd,sysLeaderEdit,sysLeaderDel} from '@/api/https'
import bus from '@/utils/eventBus.js';
import treeMenu from '@/components/base/treeMenu.vue'
import accountSetting from '@/components/base/AccountSetting.vue'
import permissionMixin from '@/utils/permission.js'
import DateUtils from '@/utils/dateUtils'
 export default ({
    name:'ledger',
    mixins: [permissionMixin],
    components:{treeMenu,accountSetting},
    data() {
      return{
        CATEGROY:0,
        startTime:'',
        endTime:'',
        stationId:sessionStorage.getItem("stationId") || '',
        tableData:[],
        userList:[],
        infoData:{},
        infoDialog:false,
        dialogStatusVisible:false,
        changeStatusForm:{},
        rulestatus:{
          status: [{ required: true, message: '请选择消缺状态' }],
          result: [{ required: true, message: '请输入消缺结果' }],
        },
        editLeager:false,
        dialogVisible:false,
        formLedger:{},
        stats: {
            total: 0,
            pending: 0,
            completed: 0,
            repeated: 0
        }
      }
    },
    mounted(){
        this.initBasin()
        this.initDefaultTime()
        this.initData()
    },
    computed: {
        permissions() {
            return this.getPermissions() || {}
        }
    },
    activated(){
       this.initBasin()
        const newStationId = sessionStorage.getItem("stationId");
        if (this.stationId != newStationId) {
            this.stationId = newStationId;
            this.initDefaultTime()
            this.initData()
        }
    },
    deactivated(){  
       bus.$off('station-changed', this.handleStationChanged);
    },
    beforeDestroy(){
       this.$refs.changeStatusForm?.clearValidate()
    },
    methods:{
        initBasin() {
            bus.$emit('showBasin', true);
            bus.$off('station-changed', this.handleStationChanged);
            bus.$on('station-changed', this.handleStationChanged);
        },
        handleStationChanged(newStationId, targetRoute) {
            if (!targetRoute || targetRoute === this.$route.name) {
                this.stationId = newStationId;
                this.initDefaultTime()
                this.initData()
            }
        },
        handleChangeCategroy(data){
            if (this.startTime && this.endTime) {
                const start = new Date(this.startTime)
                const end = new Date(this.endTime)
                
                if (end < start) {
                    this.$message.warning('结束时间不能小于开始时间！')
                    return
                }
            }
            if(data == 0){
                this.handleGetList()
            }else{
                this.handleGetListByTp()
            }
            this.CATEGROY = data
        },
        initDefaultTime() {
            this.startTime = DateUtils.formatDate(DateUtils.getDate('lastyear'))
            this.endTime = DateUtils.formatDate(DateUtils.getDate('today'))
        },
        initData(){
            GetORGUser().then(res=>{
                if(res.isSuccess && res.data && res.data.length > 0){
                    this.userList = res.data
                }else{
                    this.userList = []
                }
            })
            this.handleChangeCategroy(this.CATEGROY)
        },
        handleGetList(){
            sysLeaderGetList({
                stationID:this.stationId,
                begin:this.startTime,
                end:this.endTime
            }).then(res=>{
                if(res.isSuccess && res.data){
                    this.tableData = res.data || []
                    this.updateStats()
                }else{
                    this.tableData = []
                }
            })
        },
        updateStats() {
            this.stats.total = this.tableData.length
            this.stats.pending = this.tableData.filter(item => item.status === 0).length
            this.stats.completed = this.tableData.filter(item => item.status === 1).length
            this.stats.repeated = this.tableData.filter(item => item.repeat === 1).length
        },
        handleGetListByTp(){
            getLedgerByTp({
                stationID:this.stationId,
                CATEGROY:this.CATEGROY,
                begin:this.startTime,
                end:this.endTime
            }).then(res=>{
            if(res.isSuccess && res.data){
                this.tableData = res.data || []
                this.updateStats()
            }else{
                this.tableData = []
                this.$message.error(res.errorMessage)
            }
            })
        },
        handleChangeLedgerSet(data,val){
            const name = this.userList.filter(item =>{ return item.id == val})
            this.$confirm(`指派后不可更改，确认指派给 ${name[0].userTrueName} ？`,{
                type:'warning'
            }).then(() => {
                ledgerProssAdd({
                    Processor:val,
                    LedgerID:data.ID
                }).then(res=>{
                if(res.isSuccess){
                   this.handleChangeCategroy(this.CATEGROY)
                }else{
                    this.$message.error(res.errorMessage)
                }
                })
            }).catch(() => {}); 
        },
        handleGetLedgerInfo(data){
            getLedgerProcess({
                Sys_LedgerID:data.ID
            }).then(res=>{
            if(res.isSuccess && res.data.length > 0){
                this.infoDialog = true
                this.infoData = res.data[0]
            }else{
                this.$message.error('暂无详情')
                this.infoData = {}
            }
            })
        },
        handleSetStatus(data){
            this.changeStatusForm = {
                ID:data.ID,
                UserId:data.recorder,
                result:'',
                status:1
            }
            this.dialogStatusVisible = true
        },
        handleSaveStatus(){
            this.$refs['changeStatusForm'].validate((valid) => {
                if (valid) {
                    sysLeaderSetStatus(this.changeStatusForm).then(res=>{
                        if(res.isSuccess){
                            this.handleChangeCategroy(this.CATEGROY)
                            this.dialogStatusVisible = false
                        }else{
                            this.$message.error(res.errorMessage)
                        }
                    })
                } else {
                    return false;
                }
            });
        },
        handleAddLedger(isEdit,data){
            this.editLeager = isEdit
            this.dialogVisible = true
            if(isEdit){
                this.formLedger = {...data}
                this.formLedger.foundTime = DateUtils.formatDate(DateUtils.getDate('today'))
            }else{
                const _data = {}
                _data.foundTime = DateUtils.formatDate(DateUtils.getDate('today'))
                _data.recorderName = localStorage.getItem('userName')
                this.formLedger = {..._data}
            }
        },
        handleClose(){
            this.formLedger = {}
            this.editLeager = false
        },
        handleSaveForm() {
            const formData = this.prepareFormData()
            const apiCall = this.editLeager ? sysLeaderEdit : sysLeaderAdd
            
            apiCall(formData).then(res => {
                if(res.isSuccess){
                    this.handleClose()
                    this.handleChangeCategroy(this.CATEGROY)
                } else {
                    this.$message.error(res.errorMessage)
                }
            })
        },
        prepareFormData() {
            const baseData = {
                sys_Ledger_Process: this.formLedger.Processor ? {
                ID: 0,
                assigner: 0,
                Processor: this.formLedger.Processor,
                ProcessTime: "",
                LedgerID: this.editLeager ? this.formLedger.ID : 0
                } : {}
            }
            
            const ledgerData = { ...this.formLedger }
            delete ledgerData.Processor
            
            if (!this.editLeager) {
                ledgerData.StationID = this.stationId
                ledgerData.ID = 0
                ledgerData.status = 0
            }
            
            baseData.sys_Ledger = ledgerData
            return baseData
        },
        handleDelLedger(data){
            this.$confirm(`确认删除该条台帐记录？删除后不可恢复，请谨慎操作！`,'提示',{
                type:'warning',
                confirmButtonText: '确定删除',
                cancelButtonText: '取消',
                confirmButtonClass: 'el-button--danger',
            }).then(() => {
                sysLeaderDel({
                    ID:data.ID
                    }).then(res=>{
                    if(res.isSuccess){
                        this.$message.success('已成功删除！')
                        this.handleChangeCategroy(this.CATEGROY)
                    }else{
                        this.$message.error(res.errorMessage)
                    }
                })
            }).catch(() => {});  
        },
        changeCategroy(){
            const _d = {...this.formLedger}
            _d.tp = ''
            this.formLedger = {..._d}
        }
    }
})
</script>

<style scoped lang="scss">
.mainContent{
    height:calc(100vh - 108px);
    box-sizing: border-box;
    .searchForm{
        padding:10px 20px;
        box-sizing: border-box;
        height: 60px;
    }
}
::v-deep .el-form-item--mini.el-form-item, .el-form-item--small.el-form-item{
    margin-bottom: 0px !important;
}
.tableContent{
  height:calc(100vh - 190px);
  display: grid;
  padding:10px;
  box-sizing: border-box;
  margin-top: 10px;
}
.stats-info {
    display: flex;
    gap: 10px;
    padding: 8px 16px;
    background-color:#F4F4F5;
    border-radius:4px;
    margin-bottom: 10px;
    .stat-item {
        display: flex;
        align-items: center;
        font-size: 12px;
        color: #909399;
        
        i {
            margin-right: 5px;
        }
    }
}
/* 对话框样式 */
.info-dialog .info-content,
.status-dialog .status-form,
.ledger-dialog .ledger-form,
.inspection-dialog .inspection-content,
.online-dialog .online-content {
  padding: 10px 0;
}

.tree-container {
  height: 300px;
  overflow-y: auto;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
}

.select-field {
  display: flex;
  align-items: center;
}

.readonly-field {
  color: #909399;
  font-size: 14px;
}
</style>